package kmp;

import java.util.Arrays;

/**
 * @program: data_structures_algorithms
 * @description: kmp匹配
 * @author: lld
 * @create: 2020-11-17 20:16
 **/
public class Kmp1 {
    public static void main(String[] args) {
        String str1 = "abcabcabcaabcabcdabcaaabbcd";
        String str2 = "abcdaba";
        int[] next = kmpNext(str2);
        System.out.println(Arrays.toString(next));
        int kmpMatch = kmpMatch(str1, str2, next);
        if (kmpMatch == -1) {
            throw new RuntimeException("没有匹配到");
        } else {
            System.out.println(str1.substring(kmpMatch, kmpMatch + str2.length()));
        }
    }

    /**
     * @Description: kmp匹配
     * @Param: [str1 源字符串, str2 子串, next 子串的部分匹配值]
     * @return: -1：没有匹配，返回
     **/
    public static int kmpMatch(String str1, String str2, int[] next) {
        for (int i = 0, j = 0; i < str1.length(); i++) {
            while (j > 0 && str1.charAt(i) != str2.charAt(j)) {//
                j = next[j - 1];//调整j的大小
            }
            if (str1.charAt(i) == str2.charAt(j)) {
                j++;
            }
            if (j == str2.length()) {
                return i - j + 1;
            }
        }
        return -1;
    }

    //获取字符串的部分匹配值
    public static int[] kmpNext(String str) {
        //数组保存部分匹配值
        int[] next = new int[str.length()];
        next[0] = 0;//字符串的第一个匹配值始终为0
        for (int i = 1, j = 0; i < str.length(); i++) {
            while (j > 0 && str.charAt(i) != str.charAt(j)) {//出现
                j = next[j - 1];//为什么不直接=0
            }
            if (str.charAt(i) == str.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }
}
